package face.pay.open.task;

import com.face.pay.SecurityConfig;
import com.face.pay.WxApiConfig;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import face.pay.dao.MchApplymentInfoDao;
import face.pay.dao.OemConfigInfoDao;
import face.pay.dao.OemInfoDao;
import face.pay.entity.MchApplymentInfo;
import face.pay.open.config.ApiConfigServer;
import face.pay.open.server.CertficatesServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: zkj
 * @Date: 2019/9/2 16:48
 * @Description:
 */
@Component
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling
@Slf4j
public class ApplyMentStatusTask {


    private static final String domain = "api.mch.weixin.qq.com";


    @Autowired
    private OemConfigInfoDao oemConfigInfoDao;

    @Autowired
    private OemInfoDao oemInfoDao;

    @Autowired
    private ApiConfigServer wxApiConfigServer;


    @Autowired
    private CertficatesServer certficatesServer;

    @Autowired
    private MchApplymentInfoDao mchApplymentInfoDao;


    @Scheduled(cron = "0 0/10 * * * ?")
    @Async
    public void applymentCheck(){

        log.info("检测商户进件情况");

        /**
         * 查询所有进件记录 状态
         * 不是 REJECTED FROZEN FINISH
         */
        String [] statusArray = new String[]{
            "AUDITING","TO_BE_SIGNED"
        };

        List<MchApplymentInfo> list = this.mchApplymentInfoDao.queryListByStatus(statusArray);

        /**
         * 按照OEM 分类
         */
        Integer length = list.size();

        log.error("查询审核个数"+length);

        if(length>0){
            Map<Integer, List<MchApplymentInfo>> collect = list.stream()
                    .collect(Collectors.groupingBy(MchApplymentInfo::getOemId));

            Set<Integer> keySet = collect.keySet();

            for(Integer oemId :keySet){
                /**
                 *
                 */
                log.info("oemId:"+oemId+"进件情况查询");
                WxApiConfig config = wxApiConfigServer.getConfig(oemId);
                SecurityConfig securityConfig = config.getSecurityConfig();

                List<MchApplymentInfo> applys = collect.get(oemId);


                for(MchApplymentInfo applymentInfo: applys){

                    try{

                        Map<String, String> map =  new HashMap<>();

                        map.put("version", "1.0");

                        map.put("applyment_id", applymentInfo.getApplyment_id());
                        map.put("business_code", applymentInfo.getBusiness_code());

                        map.put("mch_id",config.getMchID());
                        map.put("sign_type", "HMAC-SHA256");
                        String nonce_str = WXPayUtil.generateNonceStr();

                        map.put("nonce_str", nonce_str);
                        String xml = WXPayUtil.generateSignedXml(map, config.getKey(), WXPayConstants.SignType.HMACSHA256);

                        log.info("调用微信进件查询接口:" + xml);
                        WXPayRequest wxPayRequest = new WXPayRequest(config);

                        String urlSuffix = "/applyment/micro/getstate";

                        String result = wxPayRequest.requestOnce(domain, urlSuffix, UUID.randomUUID().toString(), xml, 8000, 6000, true);

                        log.info("微信进件查询接口返回结果:" + result);
                        Map<String, String> resultMap = WXPayUtil.xmlToMap(result);


                        Boolean isOk = WXPayUtil.isSuccess(resultMap);

                        if(isOk){

                            Map<String, String> resultData = new HashMap<>();


                            String  applyment_state= resultMap.get("applyment_state");
                            applymentInfo.setApplyment_state(applyment_state);

                            String applyment_state_desc= resultMap.get("applyment_state_desc");

                            applymentInfo.setApplyment_state_desc(applyment_state_desc);

                            String  sub_mch_id= resultMap.get("sub_mch_id");

                            applymentInfo.setSub_mch_id(sub_mch_id);

                            String sign_url= resultMap.get("sign_url");

                            applymentInfo.setSign_url(sign_url);

                            String audit_detail= resultMap.get("audit_detail");
                            applymentInfo.setAudit_detail(audit_detail);

                            this.mchApplymentInfoDao.updateApplyMentStatus(applymentInfo);
                        }

                    }catch (Exception e){
                            log.info("查询进件状态错误",e);
                    }

                }

            }

        }
    }
}
